/**
 * ---------------------------
 * Time: 2017/8/7 20:58.
 * Author: Cangshi
 * View: http://palerock.cn
 * ---------------------------
 */
define(['app', 'zepto'], function (app) {
    'use strict';
    app.service('deviceService', function (deviceDao, PromiseUtil, ArrayUtils, logger, ObjectUtils, failureHolder, Device, MaintainPlan) {
        /**
         * [私有方法] 生成审核属性是否为空时的错误信息(对设备)
         * @param device
         * @param propertyNames
         * @returns {Array}
         */
        var buildMessageWhileDevicePropertyEmpty = function (device, propertyNames) {
            var message = [];
            ObjectUtils.whileEmptyObjectProperty(this, device, propertyNames, function (name) {
                var propertyDiscrib = null;
                switch (name) {
                    case 'deviceNo':
                        propertyDiscrib = '设备编号';
                        break;
                    case 'deviceName':
                        propertyDiscrib = '设备名称';
                        break;
                    case 'deviceDiscription':
                        propertyDiscrib = '设备描述';
                        break;
                    case 'registerInfo':
                        propertyDiscrib = '注册信息';
                        break;
                    case 'registerInfo.usedDuration':
                        propertyDiscrib = '已使用的时长';
                        break;
                    case 'registerInfo.usedDaysNumber':
                        propertyDiscrib = '已使用的天数';
                        break;
                    default:
                        propertyDiscrib = name
                }
                message.push(' [' + propertyDiscrib + ']不能为空');
            });
            return message;
        };
        /**
         * [私有方法] 生成审核属性是否为空时的错误信息(对保养计划)
         * @param maintainPlans {Array}
         */
        var buildMessageWhilePlansPropertyEmpty = function (maintainPlans) {
            if (!(maintainPlans instanceof Array)) {
                return [];
            }
            var totalErrorMessages = [];
            ArrayUtils.ergodicArrayObject(this, maintainPlans, function (maintainPlan) {
                var messages = MaintainPlan.checkItFormed(maintainPlan);
                var errorMessages = [];
                ArrayUtils.ergodicArrayObject(this, messages, function (property) {
                    switch (property) {
                        case 'maintainName':
                            errorMessages.push('保养名不能为空');
                            break;
                        case 'limitingConditionFromRunningDuration':
                            errorMessages.push('保养时长不能为空');
                            break;
                        case 'limitingConditionFromDaysNumber':
                            errorMessages.push('保养购买天数不能为空');
                            break;
                        case 'maintainContent':
                            errorMessages.push('保养内容不能为空');
                            break;
                        default:
                            break;
                    }
                });
                if (errorMessages.length > 0) {
                    totalErrorMessages.push(maintainPlan.maintainName + ':[' + errorMessages.toString() + ']')
                }
            });
            return totalErrorMessages;
        };
        /**
         * 设备注册
         * @param device {Device}
         * @param cb 成功调用
         */
        this.deviceRegister = function (device, cb) {
            // 清除不必要的属性
            device.repairRecords = [];
            device.runningRecords = [];
            var errorDeviceMessages = buildMessageWhileDevicePropertyEmpty(device, [
                'deviceNo', 'deviceName', 'deviceDiscription', 'registerInfo.usedDuration', 'registerInfo.usedDaysNumber'
            ]);
            var errorPlansMessages = buildMessageWhilePlansPropertyEmpty(device.maintainPlans);
            var errorMessages = errorDeviceMessages.concat(errorPlansMessages);
            // 若有错误则提示错误
            if (errorMessages.length > 0) {
                failureHolder.handleFailure(errorMessages, 405);
                return;
            }
            // 执行持久层操作
            deviceDao.addDevice(device, function (r, e) {
                if (e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    cb.call(window, e.message);
                }
            })
        };
        /**
         * 获取所有的设备
         * @param cb {function} 回调函数
         * @param sort {object} 排序(可选，默认不排序)[sortBy:以什么属性排序,order(可选,默认降序):升序1-降序0]
         */
        this.showAllDevices = function (cb, sort) {
            deviceDao.findAllDevices(function (r, e) {
                if (!e.code || (e.code != 200 && e.code != 404)) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    var devices = Device.toDevice(r);
                    ArrayUtils.ergodicArrayObject(this, devices, function (device) {
                        device.refreshInfo();
                    });
                    if (sort && sort.sortBy) {
                        devices = ObjectUtils.sortingArrayByProperty(devices, sort.sortBy, sort.order);
                    }
                    cb.call(window, devices, e.message);
                }
            });
        };

        /**
         * 更新设备
         * @param device
         * @param cb
         */
        this.updateDevice = function (device, cb) {
            deviceDao.updateDeviceByDeviceNoSelective(device, function (r, e) {
                if (e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    cb.call(window, e.message);
                }
            })
        };

        /**
         * 通过设备编号获取设备
         * @param deviceNo
         * @param cb
         */
        this.getDeviceByDeviceNo = function (deviceNo, cb) {
            deviceDao.findDeviceByDeviceNo(deviceNo, function (r, e) {
                if (!e.code || e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    var device = Device.toDevice(r[0]);
                    device.refreshInfo();
                    cb.call(window, device, e.message);
                }
            })
        };

        /**
         * 删除一台设备
         * @param deviceNo 设备编号
         * @param cb 成功后的回调函数
         */
        this.deleteDevice = function (deviceNo, cb) {
            deviceDao.deleteDeviceByDeviceNo(deviceNo, function (r, e) {
                if (!e.code || e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    cb.call(window, r, e.message);
                }
            });
        };

        this.checkMaintain = function (maintainPlans) {
            return buildMessageWhilePlansPropertyEmpty(maintainPlans);
        }
    })
});